package com.backend.api.exception;

import com.util.CommonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@RestControllerAdvice
public class ExceptionHanlder {

    @ExceptionHandler(value = Exception.class)
    public CommonResult commonExceptionHandler(
            HttpServletRequest httpServletRequest,
            Exception e
    ) {
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public CommonResult methodArgNotValidException(
            ConstraintViolationException cve,
            HttpServletRequest httpServletRequest
    ) {
        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();
        StringBuffer errorMsg = new StringBuffer();
        cves.forEach(ex -> errorMsg.append(ex.getMessage()));

        return CommonResult.failed(String.valueOf(errorMsg));
    }

}
